/*
 * @(#)MaintWorkflowAutomaticTaskAction.java
 *
 * Copyright (c) 2006 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.workflow.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.dms.core.FileDownloader;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.HTTPUtility;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;
import com.dcivision.workflow.WorkflowOperationConstant;
import com.dcivision.workflow.bean.WorkflowAction;
import com.dcivision.workflow.core.AutoTaskCompileException;
import com.dcivision.workflow.core.WorkflowAutomaticTaskManager;
import com.dcivision.workflow.dao.WorkflowActionDAObject;
/**
 * <p>Class Name:    MaintWorkflowAutomaticTaskAction.java    </p>
  *
 * @author           tc //mod by greatwall shao
 * @company          DCIVision Limited
 * @creation date    2006-08-23
 */
public class MaintWorkflowAutomaticTaskAction extends AbstractMaintAction {

  private static final Log log = LogFactory.getLog(MaintWorkflowAutomaticTaskAction.class);

  public MaintWorkflowAutomaticTaskAction(){
  super();
  }
  
  public String getFunctionCode() {
    return (SystemFunctionConstant.WORKFLOW_AUTOMATICTASK);
  }
  public String getListFunctionName() {
    return ("getCustomerWorkflowAutomaticTaskList");
  }
  public String getMajorDAOClassName() {
    return ("com.dcivision.workflow.dao.WorkflowActionDAObject");
  }
  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    
    MaintWorkflowAutomaticTaskForm maintForm = (MaintWorkflowAutomaticTaskForm)form;
    String opMode = maintForm.getOpMode();
    String navMode = maintForm.getNavMode();  
    
    ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
    if (forward!=null) {
      return forward;
    }
    
    if(WorkflowOperationConstant.OP_MODE_DOWNLOAD_TEMPLETE.equals(opMode)){
      try{
      this.downloadTempletes(maintForm,request,response);
      }catch(Exception e){
        log.error("Exception caught while downloading the template, maintForm=" + maintForm.toString(), e);
        addError(request,"errow.automatictask.label.template_file_not_exist");
        return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
      }
    }
    
    return super.execute(mapping, form, request, response);
  }
  
  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
   // save file[],insert into workflowAction 
    MaintWorkflowAutomaticTaskForm maintForm = (MaintWorkflowAutomaticTaskForm)form;
    
    checkDuplicatedByCategoryIDActionLablel(request, maintForm);
    
    WorkflowAutomaticTaskManager automaticTaskManager = new WorkflowAutomaticTaskManager(this.getSessionContainer(request),this.getConnection(request));
    String className=null;
    try {
      className = automaticTaskManager.getTheWholeClassName(maintForm.getSrcFile());
      maintForm.setActionClassName(className);
      super.insertRecord(mapping, form, request, response);
      //if insert success then there did not exists same class,so can save File
      className = automaticTaskManager.saveAndCompile(maintForm.getSrcFile());//can not over ride the srcFile or classFile 
    } catch (AutoTaskCompileException e) {
      log.error(e, e);
      throw new ApplicationException("automatictask.message.srcfile_err_info",e,e.toString());
    }catch(ApplicationException e){
      throw new ApplicationException("automatictask.message.srcfile_exists");
    }catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException("automatictask.message.srcfile_err_info",e,"");
    }  
  }

  /**
   * @param request
   * @param maintForm
   * @throws ApplicationException
   * @throws NumberFormatException
   */
  private void checkDuplicatedByCategoryIDActionLablel(HttpServletRequest request, MaintWorkflowAutomaticTaskForm maintForm)
      throws ApplicationException, NumberFormatException {
    WorkflowActionDAObject waDao = new WorkflowActionDAObject(this.getSessionContainer(request), this.getConnection(request));
    if (waDao.getListByWorkflowCategoryIDActionLablel(Integer.valueOf(maintForm.getCategoryObjectID()), maintForm.getActionLabel()).size() > 0) {
      throw new ApplicationException("automatictask.error.categoryIdactionLablelduplicated");
    }
  }
  
  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
   //replace file[],update workflowAction 
    MaintWorkflowAutomaticTaskForm maintForm = (MaintWorkflowAutomaticTaskForm)form;
    
    checkDuplicatedByCategoryIDActionLablel(request, maintForm);
    
    if(maintForm.getSrcFile()!=null){
     WorkflowAutomaticTaskManager automaticTaskManager = new WorkflowAutomaticTaskManager(this.getSessionContainer(request),this.getConnection(request));
    String className=null;
    try {
      className = automaticTaskManager.getTheWholeClassName(maintForm.getSrcFile());
      maintForm.setActionClassName(className);
      super.updateRecord(mapping, form, request, response);
      //if update success then there did not exists same class,so can save File
      className = automaticTaskManager.saveAndCompile(maintForm.getSrcFile());//can over Ride it
      
    }  catch (AutoTaskCompileException e) {
      log.error(e, e);
      throw new ApplicationException("automatictask.message.srcfile_err_info",e,e.toString());
    }  catch(ApplicationException ex){
      throw new ApplicationException("automatictask.message.srcfile_exists");
    }catch (Exception e) {      
      log.error(e, e);
      throw new ApplicationException("automatictask.message.srcfile_err_info",e,"");
    }
    }else{//did not upload the srcFile,Just update the basic info of workflowaction
      super.updateRecord(mapping, form, request, response);
    }
  }
  
  public void deleteRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
   //delete srcFile[],ClassFile[],workflowAction
    WorkflowActionDAObject actionDAO = new WorkflowActionDAObject(this.getSessionContainer(request), this.getConnection(request));
    MaintWorkflowAutomaticTaskForm maintForm = (MaintWorkflowAutomaticTaskForm)form;
    WorkflowAction workflowAction = (WorkflowAction)maintForm.getFormData();
    if (!Utility.isEmpty(workflowAction.getID()) && (actionDAO.isHasStep(workflowAction.getID()))) {
      throw new ApplicationException("automatictask.error.delete.info");
    }
    String classname = workflowAction.getActionClassName();
    classname = classname.replace('.', '/');
    //SessionContainer sessionContainer = (SessionContainer) request.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    WorkflowAutomaticTaskManager automaticTaskManager = new WorkflowAutomaticTaskManager(this.getSessionContainer(request),this.getConnection(request));
    automaticTaskManager.deleteSrcFile(classname+".java");//delete src file
    automaticTaskManager.deleteBinFile(classname+".class");//delete bin file
    super.deleteRecord(mapping, form, request, response);
  }
  
  private void downloadTemplete(AbstractActionForm form, HttpServletRequest request,HttpServletResponse response,Class cls) throws ApplicationException {
    //Class cls = com.dcivision.workflow.action.AutoTaskTemplate.class;
    java.security.ProtectionDomain pDomain = cls.getProtectionDomain();
    java.security.CodeSource cSource = pDomain.getCodeSource();
    java.net.URL loc = cSource.getLocation();
    String nPath=loc.toString();
    //int n=nPath.indexOf("AutoTaskTemplate.class");
    int n = nPath.lastIndexOf("/");
    String path=nPath.substring(6,n);
    String className=nPath.substring(n+1);
    className = className.substring(0,className.lastIndexOf("."));
    if (!path.endsWith("/")) {
      path += "/";
    }
    //path += "AutoTaskTemplate.java";
    path+=className+".java";
    File file = new File(path);
    
    FileInputStream inputStream = null;
    try{
      inputStream = new FileInputStream(file);      
    }catch(FileNotFoundException ex){
      throw new ApplicationException(" errow.automatictask.label.template_file_not_exist");   
    }
    
    FileDownloader fd = new FileDownloader();
    fd.setFileName(className+".java");
    fd.setContentType(HTTPUtility.CONTENT_TYPE);
    fd.setIsDownload(true);
    fd.setInputStream(inputStream);
    fd.setRequest(request);
    fd.setResponse(response);
    fd.operate();
       
  }
  
  private void downloadTempletes(AbstractActionForm form, HttpServletRequest request,HttpServletResponse response)throws ApplicationException{
    MaintWorkflowAutomaticTaskForm maintForm = (MaintWorkflowAutomaticTaskForm)form;
    Class template = null;
    if("CP".equalsIgnoreCase(maintForm.getTemplateName())){//automatic complete template
      template = com.dcivision.workflow.action.AutoTaskTemplate.class;   
    }else if("TS".equalsIgnoreCase(maintForm.getTemplateName())){//automatic trigger subworkflow template
      template = com.dcivision.workflow.action.AutoTaskStartSubWorkflowTemplate.class;
    }
    downloadTemplete(form,request,response,template);
  }
}
